package com.dlc.garbagerecyclebox.core;

import android.content.Context;
import android.text.TextUtils;

import com.dlc.commonbiz.base.DlcLogger;
import com.dlc.commonbiz.base.exception.ApiException;
import com.dlc.commonbiz.base.mqtt.bean.DlcMqttConnectOptions;
import com.dlc.commonbiz.base.mqtt.core.MqttMgr;
import com.dlc.commonbiz.base.serialport.bean.InitSerialPortGrbBean;
import com.dlc.commonbiz.base.serialport.log.SerialPortLoggerFactory;
import com.dlc.commonbiz.base.util.GsonUtil;
import com.dlc.garbagerecyclebox.GarbageRecyclerBoxCmdFactory;
import com.dlc.garbagerecyclebox.GarbageRecyclerBoxCmdProxy;
import com.dlc.garbagerecyclebox.bean.ControlBean;
import com.dlc.garbagerecyclebox.bean.GarbageRecyclerBoxBean;
import com.dlc.garbagerecyclebox.bean.HeartBeatBean;
import com.dlc.garbagerecyclebox.bean.MessageBean;
import com.dlc.garbagerecyclebox.bean.MqttInformationBean;
import com.dlc.garbagerecyclebox.callback.GarbageRecyclerBoxCallback;
import com.dlc.garbagerecyclebox.callback.GarbageRecyclerBoxCmdCallback;
import com.dlc.garbagerecyclebox.callback.GarbageRecyclerBoxProxyCallback;
import com.dlc.garbagerecyclebox.callback.MqttTopicCallback;
import com.dlc.garbagerecyclebox.log.GarbageRecycleBoxLogFactory;

/**
 * @author :      fangbingran
 * @aescription : 回收箱子管理
 * @date :        2019/08/03  11:12
 */
public class GarbageRecyclerBoxMgr {
    private static class InstanceGarbageRecyclerBoxMgr {
        private static final GarbageRecyclerBoxMgr INSTANCE = new GarbageRecyclerBoxMgr();
    }

    public static GarbageRecyclerBoxMgr get() {
        return InstanceGarbageRecyclerBoxMgr.INSTANCE;
    }

    /**
     * 语言包更改主题
     */
    private String mqttUpdateLang;
    /**
     * banner图修改主题
     */
    private String mqttUpdateBanner;
    /**
     * 更新客服电话等公司信息主题
     */
    private String mqttUpdateCompany;
    /**
     * 返回消息主题
     */
    private String mqttToFront;


    public void init(final Context context, MqttInformationBean mqttInformationBean, final GarbageRecyclerBoxBean garbageRecyclerBoxBean, final GarbageRecyclerBoxCallback callback) {
        this.mqttUpdateLang = mqttInformationBean.getMqttUpdateLang();
        this.mqttUpdateBanner = mqttInformationBean.getMqttUpdateBanner();
        this.mqttUpdateCompany = mqttInformationBean.getMqttUpdateCompany();
        this.mqttToFront = mqttInformationBean.getMqttToFront();
        GarbageRecyclerBoxProxy.get().init(context, garbageRecyclerBoxBean, new GarbageRecyclerBoxProxyCallback() {
            @Override
            public void messageArrived(String topic, String message, int messageId) {
                handleMessageArrived(topic, message, messageId);
            }

            @Override
            public void onError(ApiException apiException) {
                if (callback != null) {
                    callback.onError(apiException);
                }
            }

            @Override
            public void onOpenSerialPortSuccess() {
                if (callback != null) {
                    callback.onOpenSerialPortSuccess();
                }
            }

            @Override
            public void onOpenVisionSerialPortSuccess() {
                if (callback != null) {
                    callback.onOpenVisionSerialPortSuccess();
                }
            }

            @Override
            public void heatData(HeartBeatBean deviceBean) {
                //记录通讯异常情况
//                HeartBeatProxy.getInstance().setResultError(false, deviceBean.getDeviceAddress());
//                HeartBeatProxy.getInstance().uploadHeartBeatBeanData(deviceBean);
                if (callback != null) {
                    callback.heatData(deviceBean);
                }
            }

            @Override
            public void heatVisionData() {
                if (callback != null) {
                    callback.heatVisionData();
                }
            }
        });
    }

    public void setLog(DlcLogger dlcLogger) {
        MqttMgr.get().setMqttLogger(dlcLogger);
        GarbageRecyclerBoxCmdProxy.get().setIDlcLogger(dlcLogger);
        SerialPortLoggerFactory.createLogger(dlcLogger);
    }

    public void init(final Context context, MqttInformationBean mqttInformationBean, InitSerialPortGrbBean initSerialPortGrbBean,
                     final DlcMqttConnectOptions dlcMqttConnectOptions, final GarbageRecyclerBoxCallback callback) {
        this.mqttUpdateLang = mqttInformationBean.getMqttUpdateLang();
        this.mqttUpdateBanner = mqttInformationBean.getMqttUpdateBanner();
        this.mqttUpdateCompany = mqttInformationBean.getMqttUpdateCompany();
        this.mqttToFront = mqttInformationBean.getMqttToFront();
        GarbageRecyclerBoxProxy.get().init(context, initSerialPortGrbBean, dlcMqttConnectOptions, new GarbageRecyclerBoxProxyCallback() {
            @Override
            public void messageArrived(String topic, String message, int messageId) {
                handleMessageArrived(topic, message, messageId);
            }

            @Override
            public void onError(ApiException apiException) {
                if (callback != null) {
                    callback.onError(apiException);
                }
            }

            @Override
            public void onOpenSerialPortSuccess() {
                if (callback != null) {
                    callback.onOpenSerialPortSuccess();
                }
            }

            @Override
            public void onOpenVisionSerialPortSuccess() {
                if (callback != null) {
                    callback.onOpenVisionSerialPortSuccess();
                }
            }

            @Override
            public void heatData(HeartBeatBean deviceBean) {
                //记录通讯异常情况
//                HeartBeatProxy.getInstance().setResultError(false, deviceBean.getDeviceAddress());
//                HeartBeatProxy.getInstance().uploadHeartBeatBeanData(deviceBean);
                if (callback != null) {
                    callback.heatData(deviceBean);
                }
            }

            @Override
            public void heatVisionData() {
                if (callback != null) {
                    callback.heatVisionData();
                }
            }
        });
    }

    private void handleMessageArrived(String topic, String message, int messageId) {
        try {
            GarbageRecycleBoxLogFactory.info("收到消息====" + message);
            if (TextUtils.equals(topic, mqttToFront) && !TextUtils.isEmpty(mqttToFront)) {
                MessageBean msgBean = GsonUtil.getInstance().parseJsonStrToObj(message, MessageBean.class);
                switch (msgBean.topic) {
                    case "login":
                        //登录
                        if (mMqttTopicCallback != null && msgBean.info != null) {
                            mMqttTopicCallback.login(msgBean.type, msgBean.info.userinfo);
                        }
                        break;
                    case "updateAdvert":
                        //发布广告
                        if (mMqttTopicCallback != null) {
                            mMqttTopicCallback.updateAdvert();
                        }
                        break;
                    case "orderOperation":
                        //开门(目前没有开门的操作了)
                        if (mMqttTopicCallback != null) {
                            mMqttTopicCallback.orderOperation(msgBean);
                        }
                        break;
                    case "updateapk":
                        //更新apk
                        if (mMqttTopicCallback != null) {
                            mMqttTopicCallback.updateApk(msgBean.info.keyname, msgBean.info.downloadurl, msgBean.info.newversion);
                        }
                        break;
                    case "set":
                        //设置最大温度/开关灯时间
                        BoxMgr.getInstance()
                                .saveControlBean(new ControlBean(msgBean.starttime, msgBean.endtime, Double.parseDouble(msgBean.temp_warm)));
                        break;
                    default:
                        if (mMqttTopicCallback != null) {
                            mMqttTopicCallback.onOtherToFrontEvent(message, messageId);
                        }
                        break;
                }
            } else if (TextUtils.equals(topic, mqttUpdateLang) && !TextUtils.isEmpty(mqttUpdateLang)) {
                //语言包更改
                MessageBean msgBean = GsonUtil.getInstance().parseJsonStrToObj(message, MessageBean.class);
                if (msgBean.topic.equals("updatelang")) {
                    if (mMqttTopicCallback != null) {
                        mMqttTopicCallback.updateLang();
                    }
                }
            } else if (TextUtils.equals(topic, mqttUpdateBanner) && !TextUtils.isEmpty(mqttUpdateBanner)) {
                //轮播图修改
                if (mMqttTopicCallback != null) {
                    mMqttTopicCallback.updateBanner();
                }
            } else if (TextUtils.equals(topic, mqttUpdateCompany) && !TextUtils.isEmpty(mqttUpdateCompany)) {
                //更新客服电话等公司信息
                if (mMqttTopicCallback != null) {
                    mMqttTopicCallback.updateCompany();
                }
            } else {
                //其他自定义主题
                if (mMqttTopicCallback != null) {
                    mMqttTopicCallback.onCustomEvents(topic, message, messageId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自动订阅主题
     *
     * @param topics 主题
     * @param qos    策略
     */
    public void subscribe(String[] topics, int[] qos) {
        MqttMgr.get().subscribe(topics, qos);
    }

    /**
     * 自动订阅主题
     *
     * @param topic 主题
     * @param qos   策略
     */
    public boolean subscribe(final String topic, final int qos) {
        return MqttMgr.get().subscribe(topic, qos);
    }

    /**
     * 自动订阅主题
     *
     * @param topic 主题
     * @param qos   策略
     */
    public void addSubscribeTopics(final String topic, final int qos) {
        MqttMgr.get().addSubscribeTopics(topic, qos);
    }

    /**
     * 取消订阅主题
     *
     * @param topic 主题
     */
    public void unsubscribe(String topic) {
        MqttMgr.get().unsubscribe(topic);
    }

    /**
     * 发送订阅主题
     */
    public void publish(String topic, int qos, byte[] payload, boolean retained) {
        MqttMgr.get().publish(topic, qos, payload, retained);
    }

    /**
     * 发送订阅主题
     */
    public void publish(String topic, int qos, byte[] payload) {
        publish(topic, qos, payload, false);
    }

    /**
     * 发送订阅主题
     */
    public void publish(String topic, int qos, Object object) {
        MqttMgr.get().publish(topic, qos, object);
    }


    private MqttTopicCallback mMqttTopicCallback;


    public void setMqttTopicCallback(MqttTopicCallback mqttTopicCallback) {
        mMqttTopicCallback = mqttTopicCallback;
    }

    public void onDestroy() {
        GarbageRecyclerBoxProxy.get().onDestroy();
    }

    public void reConnect(Context context, InitSerialPortGrbBean initSerialPortGrbBean, InitSerialPortGrbBean initVisionSerialPortGrbBean,
                          GarbageRecyclerBoxCmdCallback tempCallback) {
        GarbageRecyclerBoxProxy.get().reConnect(context, initSerialPortGrbBean, initVisionSerialPortGrbBean, tempCallback);
    }

    public void reConnect(Context context, InitSerialPortGrbBean initSerialPortGrbBean,
                          GarbageRecyclerBoxCmdCallback tempCallback) {
        GarbageRecyclerBoxProxy.get().reConnect(context, initSerialPortGrbBean, tempCallback);
    }
}
